# Java 21 LTS 自动安装脚本
Write-Host "🔧 开始下载和安装 Java 21 LTS..." -ForegroundColor Green

# 设置下载参数
$javaVersion = "21.0.5"
$buildVersion = "11"
$downloadUrl = "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-$javaVersion%2B$buildVersion/OpenJDK21U-jdk_x64_windows_hotspot_$($javaVersion)_$($buildVersion).msi"
$installerPath = "$env:TEMP\OpenJDK21-installer.msi"

Write-Host "📥 下载 Java 21 LTS..." -ForegroundColor Yellow
Write-Host "下载地址: $downloadUrl" -ForegroundColor Cyan

try {
    # 下载Java 21安装包
    Invoke-WebRequest -Uri $downloadUrl -OutFile $installerPath -UseBasicParsing
    Write-Host "✅ 下载完成！" -ForegroundColor Green
} catch {
    Write-Host "❌ 下载失败，尝试备用下载地址..." -ForegroundColor Red
    
    # 备用下载地址
    $backupUrl = "https://download.java.net/java/GA/jdk21.0.2/f2283984656d49d69e91c558476027ac/13/GPL/openjdk-21.0.2_windows-x64_bin.zip"
    $zipPath = "$env:TEMP\openjdk-21.zip"
    
    try {
        Invoke-WebRequest -Uri $backupUrl -OutFile $zipPath -UseBasicParsing
        Write-Host "✅ 备用下载完成！" -ForegroundColor Green
        
        # 解压到指定目录
        $installDir = "C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot"
        Write-Host "📂 解压到: $installDir" -ForegroundColor Yellow
        
        if (!(Test-Path $installDir)) {
            New-Item -ItemType Directory -Path $installDir -Force
        }
        
        Expand-Archive -Path $zipPath -DestinationPath "C:\Program Files\Eclipse Adoptium\" -Force
        
        # 重命名解压后的文件夹
        $extractedFolder = Get-ChildItem "C:\Program Files\Eclipse Adoptium\" | Where-Object { $_.Name -like "jdk-21*" -and $_.Name -notlike "*hotspot" } | Select-Object -First 1
        if ($extractedFolder) {
            Rename-Item $extractedFolder.FullName $installDir -Force
        }
        
        Write-Host "✅ Java 21 安装完成！" -ForegroundColor Green
        
    } catch {
        Write-Host "❌ 备用下载也失败了: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "请手动下载 Java 21 LTS 从: https://adoptium.net/temurin/releases/?version=21" -ForegroundColor Yellow
        exit 1
    }
}

# 如果是MSI文件，执行安装
if (Test-Path $installerPath) {
    Write-Host "🚀 开始安装 Java 21..." -ForegroundColor Yellow
    
    try {
        Start-Process -FilePath "msiexec.exe" -ArgumentList "/i", $installerPath, "/quiet", "/norestart" -Wait
        Write-Host "✅ Java 21 安装完成！" -ForegroundColor Green
    } catch {
        Write-Host "❌ 安装失败: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "请手动运行安装程序: $installerPath" -ForegroundColor Yellow
    }
}

# 检查安装结果
Write-Host "🔍 检查 Java 安装..." -ForegroundColor Yellow
$java21Path = Get-ChildItem "C:\Program Files\Eclipse Adoptium\" | Where-Object { $_.Name -like "*jdk-21*" } | Select-Object -First 1

if ($java21Path) {
    Write-Host "✅ 找到 Java 21: $($java21Path.FullName)" -ForegroundColor Green
    
    # 设置JAVA_HOME环境变量
    $javaHome = $java21Path.FullName
    Write-Host "🔧 设置 JAVA_HOME 环境变量..." -ForegroundColor Yellow
    
    [Environment]::SetEnvironmentVariable("JAVA_HOME", $javaHome, "User")
    
    # 更新PATH环境变量
    $currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
    $javaBin = "$javaHome\bin"
    
    # 移除旧的Java路径
    $pathArray = $currentPath -split ";" | Where-Object { $_ -notlike "*jdk*\bin" -and $_ -notlike "*java*\bin" }
    $newPath = ($pathArray + $javaBin) -join ";"
    
    [Environment]::SetEnvironmentVariable("Path", $newPath, "User")
    
    # 刷新当前会话的环境变量
    $env:JAVA_HOME = $javaHome
    $env:Path = "$env:Path;$javaBin"
    
    Write-Host "✅ 环境变量设置完成！" -ForegroundColor Green
    Write-Host "JAVA_HOME: $javaHome" -ForegroundColor Cyan
    Write-Host "PATH已更新，包含: $javaBin" -ForegroundColor Cyan
    
    # 验证安装
    Write-Host "🧪 验证 Java 21 安装..." -ForegroundColor Yellow
    try {
        $javaVersionOutput = & "$javaBin\java.exe" -version 2>&1
        Write-Host "Java 版本信息:" -ForegroundColor Cyan
        Write-Host $javaVersionOutput -ForegroundColor White
    } catch {
        Write-Host "⚠️ 无法验证 Java 版本，请重新启动 PowerShell" -ForegroundColor Yellow
    }
    
} else {
    Write-Host "❌ 未找到 Java 21 安装" -ForegroundColor Red
}

# 清理下载文件
if (Test-Path $installerPath) {
    Remove-Item $installerPath -Force
}
if (Test-Path $zipPath) {
    Remove-Item $zipPath -Force
}

Write-Host "🎉 Java 21 安装脚本执行完成！" -ForegroundColor Green
Write-Host "请重新启动 PowerShell 或 IDE 以使用新的 Java 版本" -ForegroundColor Yellow